package com.yixun.qfbao.job;

import com.yixun.qfbao.model.SmsHistory;
import com.yixun.qfbao.model.dto.SmsHistoryDto;
import com.yixun.qfbao.model.enums.SendStatusEnum;
import com.yixun.qfbao.service.SmsHistoryService;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.util.email.MailConfig;
import com.yixun.qfbao.util.email.MailUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 一句话功能简述〉 〈功能详细描述〉
 * 客户到访后、认筹、认购、签约,判断生效日期是否大于流程等待时间,大于的,将报备设为无效
 * @author linyao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Component
public class SmsSendAgainJob {
	private static Logger logger = LoggerFactory.getLogger(SmsSendAgainJob.class);
	
	@Autowired
	private SmsHistoryService smsHistoryService;
	@Autowired
	private SMSUtil smsUtil;
	@Autowired
	private MailConfig mailConfig;

	@Scheduled(cron = "*/30 * * * * ?")
	public void smsSendAgain() {
		logger.info("失败短信补发,30秒一次..........job start");
		try{
			/**
			 * 获取失败短信发送记录
			 * 仅限当天
			 */
			String currentDay = DateUtils.DateToString(Calendar.getInstance().getTime(), DateStyle.YYYY_MM_DD.getValue());
			String createTimeBefore = currentDay + " 00:00:00";
			String createTimeAfter = currentDay + " 23:59:59";
			SmsHistoryDto shDto = new SmsHistoryDto();
			shDto.setSendStatus(SendStatusEnum.FAILURE.getNo());
			shDto.setCreateTimeBefore(DateUtils.stringToDate(createTimeBefore, DateStyle.YYYY_MM_DD_HH_MM_SS.getValue()));
			shDto.setCreateTimeAfter(DateUtils.stringToDate(createTimeAfter, DateStyle.YYYY_MM_DD_HH_MM_SS.getValue()));
			List<SmsHistory> shList = smsHistoryService.selectListByDto(shDto);
			if(null != shList && shList.size() > 0){
				String sendMsg = "";
				for(SmsHistory sh: shList){
					//校验重发次数是否达到上限、重发状态是否为已发送成功
					String repeatCount = sh.getRepeatCount();
					String repeatStatus = sh.getRepeatStatus();
					int currRepeatCount = 0;
					if(StringUtils.isNotBlank(repeatCount)){
						currRepeatCount = Integer.parseInt(repeatCount);
						if(3 <= currRepeatCount || "1".equals(repeatStatus) || null != sh.getOriginalId()){
							continue;
						}else{
							currRepeatCount += 1;
						}
					}


					LocalDate today = LocalDate.now();
					LocalDateTime todayBefor = LocalDateTime.of(today, LocalTime.of(0,0,0));
					LocalDateTime todayAfter = LocalDateTime.of(today, LocalTime.of(23,59,59));
					Date todayBeforDate = Date.from(todayBefor.atZone(ZoneId.systemDefault()).toInstant());
					Date todayAfterDate = Date.from(todayAfter.atZone(ZoneId.systemDefault()).toInstant());

					SmsHistoryDto smsHistoryDto = new SmsHistoryDto();
					smsHistoryDto.setReceiver(sh.getReceiver());
					smsHistoryDto.setCreateTimeBefore(todayBeforDate);
					smsHistoryDto.setCreateTimeAfter(todayAfterDate);
					smsHistoryDto.setSendStatus(SendStatusEnum.SUCCESS.getNo());
					smsHistoryDto.setExtendSql(" original_id is not null");
					int countToday = smsHistoryService.selectCountByDto(smsHistoryDto);
					if(countToday >= 20){
						SmsHistoryDto smsHis = new SmsHistoryDto();
						smsHis.setId(sh.getId());
						smsHis.setReason("(今天重发次数已达"+countToday+"次，拒绝重发，人工干预)");
						smsHis.setRepeatStatus(SendStatusEnum.SUCCESS.getNo());
						smsHis.setRepeatCount(null);
						smsHistoryService.update(smsHis);
						continue;
					}

					//發送短信.采用第一信息的通道进行补发
					//原因: 没有好用的且有钱的通道.
					Map<String, Object> returnMap = smsUtil.sendMessage(sh.getContent(), sh.getReceiver(), null, null, null);
					boolean sendStatus = (Boolean) returnMap.get("sendStatus");
					String sendRes = String.valueOf(returnMap.get("sendRes"));

					//保存短信历史信息
					SmsHistoryDto smsHis = new SmsHistoryDto();
					smsHis.setSender(smsUtil.getUserName());
					smsHis.setSender("qiaofang");
					smsHis.setReceiver(sh.getReceiver());
					smsHis.setContent(sh.getContent());
					smsHis.setSendStatus(sendStatus?SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
					smsHis.setSendRes(sendRes);
					smsHis.setOriginalId(sh.getId());
					smsHis.setRepeatCount(String.valueOf(currRepeatCount));
					smsHis.setMerchantId(sh.getMerchantId());
					smsHis.setRemark(sh.getRemark());
					smsHis.setCreateUserId(sh.getCreateUserId());
					if(returnMap.containsKey("orderUuid")){
						smsHis.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
					}
					if(returnMap.containsKey("platform")){
						smsHis.setPlatform(String.valueOf(returnMap.get("platform")));
					}
					smsHistoryService.create(smsHis);

					//修改当前短信发送次数
					smsHis = new SmsHistoryDto();
					smsHis.setId(sh.getId());
					smsHis.setRepeatStatus(sendStatus?SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
					smsHis.setRepeatCount(String.valueOf(currRepeatCount));
					smsHistoryService.update(smsHis);

					//计算当前发送次数
					if(3 == currRepeatCount && !sendStatus){
						sendMsg += "短信Id:" + String.valueOf(sh.getId())
						 	+ "<br />接收人: " + sh.getReceiver()
							+ "<br />发送内容: " + sh.getContent()
							+ "<br />*****************************<br />";
					}
				}
				if(StringUtils.isNotBlank(sendMsg)){
					String subject = "补发三次失败的短信";
					String content = sendMsg;
					logger.warn("短信补发失败三次,内容:", sendMsg);
					//sendMail(subject, content);
				}
			}
		}catch (Exception ex){
			logger.error("补发短信失败: {}", ex);
		}
		logger.info("失败短信补发,30秒一次..........job end");
	}

	/**
	 * 发送提醒邮件
	 * @param subject 标题
	 * @param content 内容
	 */
	public void sendMail(String subject, String content){
		/*
		MailConfig config = new MailConfig();
		config.setSmtp("smtp.exmail.qq.com");
		config.setPort("25");
		config.setEmail("songjianhua@yixuninfo.com");
		config.setEmailName("JHSong");
		config.setUserName("songjianhua@yixuninfo.com");
		config.setPassword("12345Abcde");
		*/
		//发送通知给相关人员
		MailUtil.sendProcess(mailConfig, mailConfig.getReceiver(), null, null, subject, content, null);
	}

}
